# -*- coding: utf-8 -*-
"""
Created on Wed May 12 15:53:40 2021

@author: Apple
"""

import sympy as sp
import math
import numpy as np
import pandas as pd

import os
import sys

class Logger(object):
    def __init__(self, filename="Default.log"):
        self.terminal = sys.stdout
        self.log = open(filename, "a")
 
    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)
 
    def flush(self):
        pass

def functiongx(x):
    gx = math.log(x+2)
    return gx

def literation(x,error):
    gx = functiongx(x)
    K = []
    while abs(gx-x)>=error:
        k = []
        k.append(x)
        k.append(gx)
        K.append(k)
        x = gx
        gx = functiongx(x)
    return K

def main(x0,error):
    
    type = sys.getfilesystemencoding()
    sys.stdout = Logger('scheme1.txt')
    
    x = sp.symbols('x')
    y = x - sp.log(x+2)
    
    print('函数表达式为: f(x) =',y)
    print('初始近似值x0为%.2f'%x0)
    
    K = literation(x0,error)
    # print(K)
    
    df = pd.DataFrame(K,columns=['xk','f(xk)'])
    
    print(f'计算精度为{error}')
    print(f'经过{len(K)}次迭代后，xk的值为{K[-1][1]}，此时f(xk)={K[-1][1] - functiongx(K[-1][1])}')
    print('迭代法求解结果如下：')
    print(df)

if __name__=="__main__":
    x = 0
    error = 0.0005
    main(x,error)

# x = 0
# error = 0.0005
# K = literation(x,error)
# print(K)